import Vue from "vue"
// import {
//   MessageBox
// } from "element-ui"

import {
  randomStr
} from "@/utils/util"

// 基础组件
export default class BasicWidget {
  constructor(widgetProps, widgetPropDescribe) {
    this.widgetPropDescribe = widgetPropDescribe
    // 组件 id
    this.id = randomStr(8, "ultrame", "_")
    // 组件在 selectedWidgets 里的索引
    this.index = -1;
    // 父组件的 id
    this.parentId = "";
    this.requiredRule = [],
      // 组件配置选项
      this.widgetProps = new Proxy(widgetProps, {
        get: (target, key) => {
          // const prop = target.find(item => item.field === key) || {}
          // const value = Reflect.get(prop, "value")
          // if (["required"].includes(key)) {
          //   if (key === "required") {
          //     value ? window.formPropsController.addRequiredRule(this.config.field, {
          //       required: true,
          //       message: `请输入${this.config.label}`,
          //       trigger: "blur"
          //     }, 0) : window.formPropsController.removeRequiredRule(this.config.field, 0)
          //   }
          // }
          const value = Reflect.get(target, key)
          if (key === "required") {
            value ? this.addRequiredRule({
              required: true,
              message: `请输入${this.widgetProps.label}`,
              trigger: "blur"
            }) : this.removeRequiredRule()
          }
          return value
        },
        set: (target, key, value) => {
          // const prop = target.find(item => item.field === key) || {}
          // if (["field"].includes(key)) {
          //   if (key === "field") {
          //     console.log(this.config[key])
          //     console.log("xxxxxxxxxxxxxxxxxxxxxx", value)
          //     if (window.formPropsController.getRulesByField(value)) {
          //       MessageBox.confirm(`已绑定有相同的字段，继续将覆盖 ${value} 字段的验证规则`, "提示", {
          //         confirmButtonText: '确定',
          //         cancelButtonText: '取消',
          //         type: 'warning'
          //       }).then(() => {
          //         console.log("yes")
          //       }).catch(() => {
          //         console.log("No")
          //       })
          //     }
          //   }
          // }
          // const result = Reflect.set(prop, "value", value)
          // if (key !== "model") {
          //   this.updateWidgetHtml()
          // }
          // return result
          this.updateWidgetHtml()
          return Reflect.set(target, key, value)
        }
      })
  }
  /**
   * 生成组件的 html 代码
   * @param {number} index 当前组件在 selectedWidgets 里的索引
   * @returns 
   */
  createWidgetHtml(index, editting, parentId) {
    this.index = index;
    this.parentId = parentId;
    const {
      label,
      labelWidth,
      required,
      field,
      placeholder,
      prefixIcon,
      suffixIcon,
      clearable,
      disabled,
      readonly,
      maxLength,
      minLength,
      prefix,
      suffix
    } = this.widgetProps;
    return (
      editting ?
      `<div
        id=${this.id}
        data-parentid=${parentId || "ultrame-canvas"}
        data-idx=${index}
        class="ultrame-form-item-box"
        data-action="move"
        draggable="true">
        <span
          class="${required ? 'required' : ''} label"
          style="width: ${labelWidth}px;">
          ${label}
        </span>
        <div class="inputContainer">
          <${this.tag}
            v-model="${field}"
            placeholder="${placeholder}"
            prefix-icon="${prefixIcon}"
            suffix-icon="${suffixIcon}"
            maxLength="${maxLength}"
            minLength="${minLength}"
            :clearable=${clearable}
            :disabled="${disabled}"
            :readonly="${readonly}">
            ${
              prefix && "<template slot='prepend'>" + prefix + "</template>"
            }
            ${
              suffix && "<template slot='append'>" + suffix + "</template>"
            }
          </${this.tag}>
        </div>
      </div>` :
      `<el-form-item
        label="${label}"
        label-width="${labelWidth}px"
        :required="${required}">
        <${this.tag} 
          v-model="formData.${field}"
          placeholder="${placeholder}"
          prefix-icon="${prefixIcon}"
          suffix-icon="${suffixIcon}"
          :clearable=${clearable}
          :disabled="${disabled}"
          :readonly="${readonly}">
        </${this.tag}>
      </el-form-item>`
    )
  }
  /**
   * 获取组件的所有属性
   * @returns 
   */
  getWidgetProps() {
    return this.widgetProps
  }
  getWidgetPropDescribe() {
    return this.widgetPropDescribe
  }
  /**
   * 更新组件的 html
   */
  updateWidgetHtml() {
    setTimeout(() => {
      const Temp = Vue.extend({
        template: this.createWidgetHtml(this.index, true, this.parentId),
        data: () => {
          const reactiveData = {};
          const updateReactiveData = () => {
            // 解决row里面的组件没初始化v-model绑定的值
            if (Array.isArray(this.widgets)) {
              this.widgets.forEach(widget => {
                Vue.set(reactiveData, widget.widgetProps.field, this.defaultValue)
              })
            } else {
              Vue.set(reactiveData, this.widgetProps.field, this.defaultValue)
            }
          }
          updateReactiveData()
          return reactiveData
        },
      });
      new Temp().$mount(`#${this.id}`);
    }, 0)
  }

  addRequiredRule(rule) {
    this.requiredRule = [rule]
  }
  removeRequiredRule() {
    this.requiredRule = []
  }
}